//
//  ImagePicker.swift
//  ptbuy
//
//  Created by MyMac on 2024/11/8.
//  拍照、选择相册
//

import SwiftUI
import UIKit

struct ImagePicker: UIViewControllerRepresentable {
    @Binding var isImagePickerPresented: Bool
    @Binding var medias:[String] // 图片数组，替换成你的图片名称
    @Binding var type:Int8;//0:拍照;1:选择相册
    @Binding var photo:Int8//记录已有照片数
    
    
    
    func makeCoordinator() -> Coordinator {
        return Coordinator(parent: self)
    }

    func makeUIViewController(context: Context) -> UIImagePickerController {
        let picker = UIImagePickerController()
        /**
         camera：拍照
         photoLibrary：选择相册
         */
        if(type==0){
            picker.sourceType = .camera
        }else{
            picker.sourceType = .photoLibrary
        }
       
        picker.allowsEditing = false
        picker.delegate = context.coordinator
        return picker
    }

    func updateUIViewController(
        _ uiViewController: UIImagePickerController,
        context: Context
    ) {
    }

    class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
        var parent: ImagePicker
        init(parent: ImagePicker) {
            self.parent = parent
        }
        func imagePickerController(
            _ picker: UIImagePickerController,
            didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]
        ) {
            if let image = info[.originalImage] as? UIImage {
                let fileName = UUID().uuidString.replacingOccurrences(of: "-", with: "")+".jpg"
                Utils.saveImage(image:image,fileName:fileName)
                parent.medias.append(fileName)
                parent.photo=parent.photo+1
                
                
                // Save image to the app's document directory and get the file path
//                if let imageData = image.jpegData(compressionQuality: 1.0) {
//                    let fileManager = FileManager.default
//                    let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
//                    let fileURL = documentsURL.appendingPathComponent(
//                        UUID().uuidString.replacingOccurrences(of: "-", with: "")+".jpg"
//                    )
//                   
//                    do {
//                        try imageData.write(to: fileURL)
//                        parent.medias.append(fileURL.path)
//                        parent.photo=parent.photo+1
//                    } catch {
//                        print("Failed to save image: \(error)")
//                    }
//                }
            }
            parent.isImagePickerPresented = false
        }

        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            parent.isImagePickerPresented = false
        }
        
        

    }
}


